﻿/******************************************************************************
    myBoard is a port of MacOS X dashboard application for windows.
    Copyright (C) 2007,2008  by Yann ALET
    Email : yann.alet@gmail.com

    myBoard is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    myBoard is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using myBoard.Framework;
using System.Windows.Media.Animation;
using System.Diagnostics;
using System.Windows.Threading;

namespace WeatherMagnet
{
	/// <summary>
	/// Interaction logic for Magnet.xaml
	/// </summary>
	public partial class Magnet : IMagnet , IRequiresStorage, IFlip
	{
        XmlDataProvider _citiesLookupXmlDataProvider;
        XmlDataProvider _weatherXmlDataProvider;
        Storage _storage;
        Settings _settings;
        Storyboard _contractCities;
        Storyboard _expandCities;
        string _currentFeed;
        DispatcherTimer _refresher;
            
        public Magnet()
		{
			this.InitializeComponent();
            _currentFeed = string.Empty;
            _flipToBackBt.Click += new RoutedEventHandler(_flipToBackBt_Click);
            _doneBt.Click += new RoutedEventHandler(_doneBt_Click);
            _cityTbx.KeyUp += new KeyEventHandler(_cityTbx_KeyUp);
            _citiesLookupXmlDataProvider = this.Resources["CountriesXMLSource"] as XmlDataProvider;
            _weatherXmlDataProvider = this.Resources["WeatherXMLDataSource"] as XmlDataProvider;
            _contractCities = this.Resources["ContractCities"] as Storyboard;
            _expandCities = this.Resources["ExpandCities"] as Storyboard;
            _contractCities.Completed += new EventHandler(_contractCities_Completed);
            _accuWeatherHomePageLink.MouseLeftButtonUp += new MouseButtonEventHandler(_accuWeatherHomePageLink_MouseLeftButtonUp);
            _linkDay1.Click += new RoutedEventHandler(_linkDay_Click);
            _linkDay2.Click += new RoutedEventHandler(_linkDay_Click);
            _linkDay3.Click += new RoutedEventHandler(_linkDay_Click);
            _linkDay4.Click += new RoutedEventHandler(_linkDay_Click);
            _linkDay5.Click += new RoutedEventHandler(_linkDay_Click);
            _refresher = new DispatcherTimer();
            _refresher.Interval = new TimeSpan(0, 5, 0);
            _refresher.Tick += new EventHandler(_refresher_Tick);
		}

        ~Magnet()
        {
            Debug.WriteLine("Destroying weather magnet");
        }

        void _refresher_Tick(object sender, EventArgs e)
        {
            _weatherXmlDataProvider.Source = new Uri(_currentFeed);
            _weatherXmlDataProvider.Refresh();
        }

        void _linkDay_Click(object sender, RoutedEventArgs e)
        {
            Connector.HideMyBoard();
            Process.Start((((System.Xml.XmlElement)(((Button)sender).Content))).InnerText);
        }

        void _accuWeatherHomePageLink_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Connector.HideMyBoard();
            Process.Start("http://www.accuweather.com/");
        }

        void _contractCities_Completed(object sender, EventArgs e)
        {
            FlipRequested(MagnetSides.Front);
        }

        void _cityTbx_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                this.BeginStoryboard(_expandCities);
                _citiesLookupXmlDataProvider.Source = new Uri(string.Format("http://myboard.accu-weather.com/widget/myboard/city-find.asp?location={0}", _cityTbx.Text));                
                //_citiesLookupXmlDataProvider.Source = new Uri("http://localhost:8081/city-find.xml");
            }
        }

        void _doneBt_Click(object sender, RoutedEventArgs e)
        {
            if (_citiesLbx.SelectedItem != null)
            {
                _settings.Location = ((System.Xml.XmlElement)(_citiesLbx.SelectedItem)).Attributes["location"].Value;
                string metric = _metricsLbx.Text == "C°" ? "1" : "0";
                _currentFeed = string.Format("http://myboard.accu-weather.com/widget/myboard/weather-data.asp?location={0}&metric=" + metric, _settings.Location);
                //_currentFeed = "http://localhost:8081/weather-data.xml";
                _weatherXmlDataProvider.Source = new Uri(_currentFeed);                
            }
            this.BeginStoryboard(_contractCities);
        }

        void _flipToBackBt_Click(object sender, RoutedEventArgs e)
        {
            FlipRequested(MagnetSides.Back);
        }

        #region IMagnet Members

        public string StoreID 
        {
            get
            {
                return "{94C5F454-0299-4616-9772-BBA93BDD550C}";
            }
        }

        public event OnFlipRequested FlipRequested;

        public Panel GetBackSide()
        {
            return _back;
        }

        public Panel GetFlipZone()
        {
            return _flip;
        }

        public Panel GetFrontSide()
        {
            return _front;
        }

        public BitmapImage Icon
        {
            get
            {
                return ResourcesAccess.GetBitmapImageFromResource(string.Format("WeatherMagnet.Images.{0}.png", "Icon"));                
            }
        }

        BitmapImage _thumbnail;

        public BitmapImage Thumbnail
        {
            get
            {
                if (_thumbnail == null)
                {
                    _thumbnail = Tools.GetBitmapImageFromFrameworkElement(this);
                }
                return _thumbnail;
                
                
                //return ResourcesAccess.GetBitmapImageFromResource("WeatherMagnet.Images.Thumbnail.png");
            }
        }

        public string MagnetName
        {
            get { return "Weather"; }
        }

        public void Terminate()
        {
            _refresher.Stop();
            _refresher = null;
        }

        public void SaveState()
        {
            Serialization.Serialize(_settings, System.IO.Path.Combine(_storage.StorageDirectory.FullName, "Settings.xml"));
        }

        #endregion

        #region IRequiresStorage Members

        public void GetStorage(Storage storage)
        {
            _storage = storage;
            _settings = Serialization.DeSerialize(System.IO.Path.Combine(storage.StorageDirectory.FullName,"Settings.xml"));
            string metric = _metricsLbx.Text == "C°" ? "1" : "0";
            _currentFeed = string.Format("http://myboard.accu-weather.com/widget/myboard/weather-data.asp?location={0}&metric=" + metric, _settings.Location);
            //_currentFeed = "http://localhost:8081/weather-data.xml";
            _weatherXmlDataProvider.Source = new Uri(_currentFeed);
            _refresher.Start();
        }

        #endregion
    }
}